<?php

namespace app\health\controller;

use app\health\model\HealthUser;
use app\health\model\HealthUserAccount;
use app\health\model\HealthUserTask;
use app\health\model\HealthWebsiteTask;
use app\health\model\HealthWebsiteVideo;
use think\Db;

/**
 * 会员接口
 */
class UserTask extends ApiBase
{
    protected $noNeedLogin = ['index', 'index_v2'];

    /**
     * 网赚任务
     * @Author 张旭鹏
     * @DateTime 2023-07-17
     */
    public function index(): void
    {
        $page_title = '我的任务';
        $rules      = [
            '用户完成视频浏览任务后可获取相应红包奖励金，具体金额以页面任务展示为准。',
            '完成任务后可在“我的”——“我的红包”内查看奖励金额。红包可用于提现或在鑫互助小程序商城购物使用。'
        ];
        $tips       = '';
        $isGetTask  = ['disposable' => [], 'today' => [], 'month' => []];
        if ($this->auth->id) {
            $doTask     = HealthUserTask::where('user_id', $this->auth->id)->where('status', '1')->select();
            $total      = 0;
            $awardValue = 0;
            foreach ($doTask as $row) {
                $total += 1;
                if ($row->award_type == 1) {
                    $awardValue = bcadd($awardValue, $row->award_value, 2);
                }
                $isGetTask['disposable'][] = $row->task_id;
                if (date('Y-m-d', $row->complete_time) === date('Y-m-d')) {
                    $isGetTask['today'][] = $row->task_id;
                }
                if (date('Y-m', $row->complete_time) === date('Y-m')) {
                    $isGetTask['month'][] = $row->task_id;
                }
            }
            $isGetTask['disposable'] = array_unique($isGetTask['disposable']);
            $isGetTask['month']      = array_unique($isGetTask['month']);
            $tips                    = "已完成{$total}个任务，累计获得{$awardValue}元";
        }
        $taskList  = HealthWebsiteTask::where('status', 1)
            ->where('online', 1)
            ->where('category', 'in', [1, 2])->select();
        $task_data = [];
        foreach ($taskList as $task) {
            $isGet = 0;
            switch ($task['category']) {
                case 1:
                    $category = 'today';
                    break;
                case 2:
                    $category = 'month';
                    break;
                case 3:
                    $category = 'disposable';
                    break;
            }
            $isGet       = in_array($task['id'], $isGetTask[$category]) ? 1 : 0;
            $task_data[] = [
                'id'           => $task['id'],
                'name'         => $task['name'],
                'complete_num' => $task['complete_num'],
                'description'  => $task['description'],
                'award_type'   => $task['award_type'],
                'award_value'  => $task['award_value'],
                'is_get'       => $isGet,
            ];
        }
        $this->success('', compact('page_title', 'rules', 'tips', 'task_data'));
    }

    public function index_v2(): void
    {
        $page_title   = '我的任务';
        $rules        = [
            '用户完成视频浏览任务后可获取相应红包奖励金，具体金额以页面任务展示为准。',
            '完成任务后可在“我的”——“我的红包”内查看奖励金额。红包可用于提现或在鑫互助小程序商城购物使用。'
        ];
        $tips         = '';
        $completeTask = [];
        $receiveTask  = [];
        $receiveToId  = [];
        if ($this->auth->id) {
            $complete     = HealthUserTask::getCompleteInfo($this->auth->id);
            $tips         = $complete['tips'];
            $completeTask = $complete['complete_task'];
            $receiveTask  = $complete['receive_task'];
            $receiveToId  = $complete['receive_to_id'];
        }
        $task_data = [
            'system' => ['name' => '系统任务', 'lists' => []],
            'daily'  => ['name' => '视频任务', 'lists' => []]
        ];
        $taskList  = HealthWebsiteTask::where('status', 1)->where('online', 1)->select();
        foreach ($taskList as $task) {
            $receive_id = 0;
            if (in_array((int)$task['id'], $receiveTask, true)) {
                $isGet      = 2;//已领取
                $receive_id = $receiveToId[$task['id']];
            } else if (in_array((int)$task['id'], $completeTask, true)) {
                $isGet = 1;//待领取
            } else {
                $isGet = 0;//待完成
            }
            $currentItem = [
                'id'           => $task['id'],
                'name'         => $task['name'],
                'complete_num' => $task['complete_num'],
                'description'  => $task['description'],
                'award_type'   => $task['award_type'],
                'award_value'  => $task['award_value'],
                'is_get'       => $isGet,
                'complete_way' => $task['complete_way'],
                'to_page'      => HealthWebsiteTask::getCompleteToPage($task['complete_way']),
                'receive_id'   => $receive_id
            ];
            if (in_array($task['category'], [1, 2], true)) {
                $task_data['daily']['lists'][] = $currentItem;
            } else {
                $task_data['system']['lists'][] = $currentItem;
            }
        }
        sort($task_data);
        $this->success('', compact('page_title', 'rules', 'tips', 'task_data'));
    }

    /**
     * 做任务
     * @Author 张旭鹏
     * @DateTime 2023-07-17
     */
    public function do(): void
    {
        $params = $this->request->param();
        $result = $this->validate($params, ['task_id|任务id' => 'require']);
        if ($result !== true) {
            $this->error($result);
        }
        $detail = HealthWebsiteTask::where('id', $params['task_id'])
            ->where('online', 1)
            ->find();
        if (!$detail) {
            $this->error('任务不存在');
        }
        if ($detail->status !== 1) {
            $this->error('任务已下线');
        }
        $category      = $detail->category;
        $userTaskWhere = [
            'user_id' => ['=', $this->auth->id],
            'task_id' => ['=', $detail['id']],
        ];
        if ($category === 1) {
            $userTaskWhere['created_at'] = ['between time', ['today', 'tomorrow']];
        }
        if ($category === 2) {
            $userTaskWhere['created_at'] = ['between time', ['first Day of this month 00:00:00', 'first Day of next month 00:00:00']];
        }
        $userTask = HealthUserTask::where($userTaskWhere)->find();
        if ($userTask && $userTask->status === 1) {
            $this->error('任务已完成');
        }
        $uniqId = uniqid('user_task', true);
        $key    = password_hash($uniqId, PASSWORD_DEFAULT);
        if (!$userTask) {
            $userTask = HealthUserTask::create([
                'user_id'           => $this->auth->id,
                'task_id'           => $detail['id'],
                'task_category'     => $detail['category'],
                'award_type'        => $detail['award_type'],
                'award_value'       => $detail['award_value'],
                'task_complete_num' => $detail['complete_num'],
                'key'               => $key
            ]);
        } else {
            $userTask->key = $key;
            $userTask->save();
        }
        $complete_way_content = $detail['complete_way_content'];
        if ($detail['complete_way'] === 1) {
            $video                                  = HealthWebsiteVideo::where('id', $complete_way_content['video_id'])->find();
            $complete_way_content['video_name']     = $video['name'];
            $complete_way_content['video_src']      = $video['url'];
            $complete_way_content['video_cover']    = $video['cover'];
            $complete_way_content['video_duration'] = $video['duration'];
        }
        $this->success('', [
            'complete_way'         => $detail['complete_way'],
            'complete_way_content' => $complete_way_content,
            'user_task_id'         => $userTask['id'],
            'user_task_key'        => $uniqId
        ]);
    }

    /**
     * 完成任务
     * @Author 张旭鹏
     * @DateTime 2023-07-17
     */
    public function complete(): void
    {
        $params = $this->request->param();
        $result = $this->validate($params, [
            'task_id|任务id'            => 'require',
            'user_task_id|用户任务ID'   => 'require',
            'user_task_key|用户任务KEY' => 'require',
        ]);
        if ($result !== true) {
            $this->error($result);
        }
        try {
            Db::startTrans();
            $userTask = HealthUserTask::where([
                'user_id' => $this->auth->id,
                'task_id' => $params['task_id'],
                'id'      => $params['user_task_id'],
            ])->with(['task'])->lock(true)->find();
            if (!$userTask) {
                throw new \Exception('任务异常');
            }
            if ($userTask->status === 1) {
                throw new \Exception('任务已完成');
            }
            if (!password_verify($params['user_task_key'], $userTask['key'])) {
                throw new \Exception('非法操作');
            }
            ++$userTask->complete_num;
            if ($userTask->complete_num >= $userTask->complete_time) {
                $userTask->complete_time = time();
                $userTask->status        = 1;
                $userTask->receive       = 1;
            }
            $userTask->save();
            if ($userTask->status === 1 && $userTask->award_value > 0) {
                HealthUser::where('id', $userTask['user_id'])->setInc($userTask->award_type === 1 ? 'balance' : 'virtually_coin', $userTask->award_value);
                HealthUserAccount::income(
                    $userTask['user_id'],
                    HealthUserAccount::FORM_TYPE_USER_TASK,
                    $userTask->award_type === 1 ? HealthUserAccount::ACCOUNT_TYPE_BALANCE : HealthUserAccount::ACCOUNT_TYPE_VIRTUALLY,
                    $userTask->award_value,
                    $userTask->task->complete_way_text
                );
            }
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success('success', ['award_type' => $userTask->award_type, 'award_value' => $userTask->award_value]);
    }

    /**
     * 领取任务奖励
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function receive(): void
    {
        $receiveId = $this->request->param('receive_id');
        $row       = HealthUserTask::where([
            'user_id' => $this->auth->id,
            'id'      => $receiveId
        ])->with(['task'])->lock(true)->find();
        if (!$row) {
            $this->error('未获取到任务记录');
        }
        if ($row['status'] !== 1) {
            $this->error('任务未完成');
        }
        if ($row['receive'] === 1) {
            $this->error('奖励已领取');
        }
        Db::transaction(static function () use ($row) {
            HealthUser::where('id', $row['user_id'])->setInc($row->award_type === 1 ? 'balance' : 'virtually_coin', $row->award_value);
            HealthUserAccount::income(
                $row['user_id'],
                HealthUserAccount::FORM_TYPE_USER_TASK,
                $row['award_type'] === 1 ? HealthUserAccount::ACCOUNT_TYPE_BALANCE : HealthUserAccount::ACCOUNT_TYPE_VIRTUALLY,
                $row['award_value'],
                $row->task->complete_way_text
            );
            $row->save(['receive' => 1]);
        });
        $this->success('领取成功');
    }
}
